package com.pentajock.docdb.dialogs;

import com.pentajock.docdb.AdminWindow;
import com.pentajock.docdb.Main;
import com.pentajock.docdb.database.DBController;
import com.pentajock.docdb.images.DBImages;
import com.pentajock.docdb.listeners.AutoTextSelectionFocusListener;
import com.pentajock.docdb.types.User;
import com.pentajock.docdb.utils.Utils;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*; 

public class ExtensionDialog extends JDialog {
	private static final String CANCEL_DIALOG_INPUT_KEY = "CANCEL_DIALOG";
	private static final String newTitle = "Create New Extension";
	private static final String editTitle = "Edit Extension: ";
	
	private String extension;
	private JButton okButton;
	private JButton cancelButton;
	
	private JTextField extensionTextField;
	private JTextField appCallTextField;
	private JTextField docCallTextField;
	private JCheckBox supPropsCheckBox;
	private JCheckBox supCustPropsCheckBox;
	private JCheckBox supHeaderCheckBox;
	private JCheckBox supCreateNewCheckBox;
	private JComboBox categoryComboBox;
	
	private boolean success;
	//private boolean newExtension;
	private boolean dialogCanceled;
	
	/* For editing an existing extension */
	public ExtensionDialog(AdminWindow owner, String extension, User adminUser) {
		super(owner, editTitle + extension, true);
		constructHelper(extension, adminUser);
	}
	
	/* For creating a new extension */
	public ExtensionDialog(AdminWindow owner, User adminUser) {
		super(owner, newTitle, true);
		constructHelper(null, adminUser);
	}
	
	private void constructHelper(String extension, User adminUser) {
		this.extension = extension;
		checkUser(adminUser);
		success = false;
		Utils.setIconImage(this, DBImages.GENERIC_ICON.getImage());
		
		initializeObjects();
		layoutFrame();
		addListeners();
		getRootPane().setDefaultButton(okButton);
		setResizable(false);
		pack();
		setLocationRelativeTo(null);
	}
	
	private void initializeObjects() {
		extensionTextField = new JTextField(extension);
		appCallTextField = new JTextField(DBController.getActiveXCall(extension));
		docCallTextField = new JTextField(DBController.getDocumentCall(extension));
		supPropsCheckBox = new JCheckBox("", DBController.supportsBuiltInProperties(extension));
		supCustPropsCheckBox = new JCheckBox("", DBController.supportsCustomProperties(extension));
		supHeaderCheckBox = new JCheckBox("", DBController.supportsHeader(extension));
		supCreateNewCheckBox = new JCheckBox("", DBController.supportsCreateNew(extension));
		categoryComboBox = new JComboBox(DBController.getCategories().toArray());
		if (categoryComboBox.getItemCount() > 0) {
			if (extension == null) {
				categoryComboBox.setSelectedItem(0);
			}
			else {
				categoryComboBox.setSelectedItem(DBController.getDefaultCategory(extension));
			}
		}
		okButton = new JButton("OK");
		okButton.setDefaultCapable(true);
		okButton.setMnemonic(KeyEvent.VK_O);
		
		cancelButton = new JButton("Cancel");
		cancelButton.setMnemonic(KeyEvent.VK_C);
	}
	
	private void layoutFrame() {
		int hAlign = SwingConstants.RIGHT;
		JLabel extensionLabel = new JLabel("Extension:", hAlign);
		extensionLabel.setDisplayedMnemonic('x');
		extensionLabel.setLabelFor(extensionTextField);
		extensionTextField.setEnabled(this.extension == null);
		try {
			extensionLabel.setIcon(DBImages.getMimeType(extension));
		}
		catch (Exception e) {}
		
		JLabel appCallLabel = new JLabel("Application Call:", hAlign);
		appCallLabel.setDisplayedMnemonic('a');
		appCallLabel.setLabelFor(appCallTextField);
		
		JLabel docCallLabel = new JLabel("Document Call:", hAlign);
		docCallLabel.setDisplayedMnemonic('d');
		docCallLabel.setLabelFor(docCallTextField);
		
		JLabel defaultCatLabel = new JLabel("Default Category:", hAlign);
		defaultCatLabel.setDisplayedMnemonic('f');
		defaultCatLabel.setLabelFor(categoryComboBox);
		
		JLabel supPropsLabel = new JLabel("Supports Properties:", hAlign);
		supPropsLabel.setDisplayedMnemonic('p');
		supPropsLabel.setLabelFor(supPropsCheckBox);
		
		JLabel supCustPropsLabel = new JLabel("Supports Custom Properties:", hAlign);
		supCustPropsLabel.setDisplayedMnemonic('c');
		supCustPropsLabel.setLabelFor(supPropsCheckBox);
		
		JLabel supHeaderLabel = new JLabel("Supports Header:", hAlign);
		supHeaderLabel.setDisplayedMnemonic('h');
		supHeaderLabel.setLabelFor(supHeaderCheckBox);
		
		JLabel supCreateNewLabel = new JLabel("Supports Create New:", hAlign);
		supCreateNewLabel.setDisplayedMnemonic('n');
		supCreateNewLabel.setLabelFor(supCreateNewCheckBox);

		JPanel extPanel = new JPanel(new GridLayout(8, 2, 4, 4));
		extPanel.add(extensionLabel);
		extPanel.add(extensionTextField);
		extPanel.add(appCallLabel);
		extPanel.add(appCallTextField);
		extPanel.add(docCallLabel);
		extPanel.add(docCallTextField);
		extPanel.add(defaultCatLabel);
		extPanel.add(categoryComboBox);
		extPanel.add(supPropsLabel);
		extPanel.add(supPropsCheckBox);
		extPanel.add(supCustPropsLabel);
		extPanel.add(supCustPropsCheckBox);
		extPanel.add(supHeaderLabel);
		extPanel.add(supHeaderCheckBox);
		extPanel.add(supCreateNewLabel);
		extPanel.add(supCreateNewCheckBox);
		
		JPanel buttonPanel = new JPanel(new FlowLayout());
		buttonPanel.add(okButton);
		buttonPanel.add(cancelButton);
		
		Container contentPane = getContentPane();
		contentPane.setLayout(new BoxLayout(contentPane, BoxLayout.Y_AXIS));
		contentPane.add(extPanel);
		contentPane.add(Box.createVerticalStrut(3));
		contentPane.add(new JSeparator(SwingConstants.HORIZONTAL));
		contentPane.add(Box.createVerticalStrut(3));
		contentPane.add(buttonPanel);
	}
	
	private void addListeners() {
		addComponentListener(new ComponentAdapter() {
			public void componentShown(ComponentEvent e) {
				//
			}
		});
		
		okButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				Object[] o = checkFields();
				if(o != null) {
					if (ExtensionDialog.this.extension == null) {
						success = DBController.addExtension(o);
						setVisible(false);
					}
					else {
						success = DBController.updateExtension(o);
						setVisible(false);
					}
				}
			}
		});
		
		cancelButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				setVisible(false);
			}
		});
		
		extensionTextField.addFocusListener(new AutoTextSelectionFocusListener(extensionTextField));
		appCallTextField.addFocusListener(new AutoTextSelectionFocusListener(appCallTextField));
		docCallTextField.addFocusListener(new AutoTextSelectionFocusListener(docCallTextField));
		
		/*
		 * Input/Action mapping.
		 */
		InputMap inputMap = new ComponentInputMap((JComponent)getContentPane());
		inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), CANCEL_DIALOG_INPUT_KEY);
		
		ActionMap actionMap = new ActionMap();
		actionMap.put(CANCEL_DIALOG_INPUT_KEY, new AbstractAction() {
			public void actionPerformed(ActionEvent e) {
				setVisible(false);
			}
		});
		
		((JComponent)getContentPane()).setInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW, inputMap);
		((JComponent)getContentPane()).setActionMap(actionMap);
		/**/
	}
	
	private Object[] checkFields() {
		String badFields = "";
		
		String extension = extensionTextField.getText().toLowerCase().trim();
		String appCall = appCallTextField.getText().trim();
		String docCall = docCallTextField.getText().trim();
		String defaultCat = categoryComboBox.getSelectedItem().toString();
		Boolean supProps = supPropsCheckBox.isSelected();
		Boolean supCustProps = supCustPropsCheckBox.isSelected();
		Boolean supHeader = supHeaderCheckBox.isSelected();
		Boolean supCreateNew = supCreateNewCheckBox.isSelected();
		
		if (extension.length() < 1) 
			badFields += "* Extension cannot be blank\n";
		if (appCall.length() < 1)
			badFields += "* Application call cannot be blank\n";
		if (docCall.length() < 1)
			badFields += "* Document call cannot be blank\n";
		if (defaultCat.length() < 1)
			badFields += "* Default Category cannot be blank\n";
		
		if (this.extension == null) { // If this is a new extension
			 if (DBController.isSupportedExtension(extension))
				 badFields += "* The extension name is already in the database";
		}
		
		if (badFields.equals("")) {
			// Order is very important - Must match DBController.addExtension
			return new Object[] {extension, appCall, docCall, defaultCat, supProps, supCustProps, supHeader, supCreateNew};
		}
		showError(badFields);
		return null;
	}
	
	private void showMessage(String message, String title) {
		JOptionPane.showMessageDialog(this, message, title, JOptionPane.INFORMATION_MESSAGE);
	}
	
	private void showError(String message) {
		JOptionPane.showMessageDialog(this, message, "Error", JOptionPane.ERROR_MESSAGE);
		Main.printDebug(message);
	}
	
	private void resetFields() {
		extensionTextField.setText("");
		appCallTextField.setText("");
		docCallTextField.setText("");
		supPropsCheckBox.setSelected(false);
		supCustPropsCheckBox.setSelected(false);
		supHeaderCheckBox.setSelected(false);
	}
	
	public void checkUser(User u) {
		if (!DBController.getUserIsAdmin(u))
			setVisible(false);
	}
	
	public boolean isSuccessful() {
		return success;
	}
	
	public void setVisible(boolean b) {
		super.setVisible(b);
		dispose();
	}
}
